<template>
  <el-dialog
    v-el-drag-dialog
    title="回执确认"
    :visible.sync="visible"
    :append-to-body="true"
    width="1024px"
    :destroy-on-close="true"
    @closed="reset"
  >
    <el-form ref="dataForm" inline :rules="rules" :model="temp">
      <el-descriptions size="medium" :column="2" style="margin-bottom: 20px;">
        <el-descriptions-item label="客户编号">{{ temp.csmCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ temp.csmName }}</el-descriptions-item>
        <el-descriptions-item label="客户地址">{{ temp.csmAddress }}</el-descriptions-item>
      </el-descriptions>
      <el-form-item label="责任机构:" prop="orgSNNo">
        <el-tree-select
          v-model="temp.orgSNNo"
          disabled
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': false,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="收款人:" prop="depReceiver">
        <el-select v-model="temp.depReceiver" disabled :loading="$loadingPlugin.getOwnersList" style="width: 120px;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" prop="paymentMethod">
        <el-select v-model="temp.paymentMethod" style="width: 150px;" disabled placeholder="请选择" @change="paymentChange">
          <el-option
            v-for="item in paymentMethodMapClone"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="确认人:" prop="reCheckUserName">
        <el-input v-model="temp.reCheckUserName" disabled style="width: 100px;" />
      </el-form-item>
      <el-form-item label="押金照片信息:" label-width="110px" prop="" style="width: 100%;">
        <AddFileList
          :default-value="temp.depositrgPic"
          :item-attrs="{
            canEdit: true,
            __config__:{
              maxNumber:5,
              title:'附件上传'
            },
            prop: 'SysUserPage_imageUrl'
          }"
          @changeFormItem="uploadUrlChange"
        />
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      :immediate-fetch="false"
      :summary-method="getSummaries"
      show-summary
      @fetch="fetchData"
    />
    <div slot="footer" class="dialog-footer">
      <div v-show="temp.isRePay === 2" class="footer-tip">已二次支付，待确认回执</div>
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button v-if="corpSettingData.sp6 >> 29 & 0x01 && temp.paymentMethod === 1 && temp.isRePay === 1" :loading="$loadingPlugin.success" type="primary" @click="showSecondPayDialog">
        二次支付
      </el-button>
      <el-button v-else :loading="$loadingPlugin.success" type="primary" @click="success">
        确认回执
      </el-button>
    </div>
    <prepaid-card ref="prepaidCard" />
    <second-pay ref="secondPay" @paySuccess="success1" @confirmPaySuccess="handleConfirmPaySuccess" />
  </el-dialog>
</template>

<script>
  import {
    queryCashPledgeDetail,
    queryCsmCardCodeByOrderCode,
    depositReceipt,
    queryOwnerList, querySpecListAll
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import PrepaidCard from './PrepaidCard'
  import { formatColumnMap } from '@/utils'
  import AddFileList from '@/views/components/NormalReceiptsAdd/components/AddFileList.vue'
  import SecondPay from './SecondPay.vue'
  export default {
    name: 'receipt-confirm',
    components: {
      PrepaidCard,
      AddFileList,
      SecondPay
    },
    props: {
      paymentMethodMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        baseUrl: 'http://image.haoyunqi.com.cn/',
        treeData: [],
        ownersList: [],
        showCsmCard: false, // 是否显示预付卡
        payDisabled: false, // 支付方式是否禁用
        check_csmCard_ok_info: {
          check_csmCard_ok_status: false, // 是否校验通过预付卡密码或验证码 true表示校验通过 false表示校验失败
          check_csmCard_ok_msg: ''
        },
        paymentMethodMapClone: [],
        csmName: '',
        csmPhone: '',
        row: {},
        temp: {
          orgSNNo: '',
          depReceiver: '',
          paymentMethod: 1,
          reCheckUserName: '',
          depositrgPic: ''
        },
        rules: {
          depReceiver: [{ required: true, message: '请选择配送员', trigger: 'change' }],
          reCheckUserName: [{ required: true, message: '请输入确认人', trigger: 'change' }],
          paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
        },
        detail: {},
        specList: [],
        order: {
          treceivables: 0
        },
        tableData: {
          column: [
            {
              prop: 'specCode',
              label: '规格型号',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit && scope.row.pricingMode === 2 ? (
                    <el-select
                      value={scope.row[scope.column.property]}
                      onChange={val => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {this.specList.map(option => {
                        return (
                          <el-option
                            label={option.specName}
                            value={option.specCode}
                          ></el-option>
                        )
                      })}
                    </el-select>
                  ) : (
                    <span>
                      {formatColumnMap(this.specList, 'specCode', scope.row[scope.column.property], 'specName')}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'goodsCount',
              align: 'right',
              label: '数量'
            },
            {
              prop: 'deposit',
              align: 'right',
              label: '单个押金(元)'
            },
            {
              prop: 'totalDeposit',
              label: '总押金(元)',
              align: 'right',
              width: 120
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'userInfo'
      ])
    },
    created() {
      this.getGoodsSpecList()
    },
    methods: {
      async open(temp) {
        console.log('temp', temp)
        if (temp) this.row = temp
        this.paymentMethodMapClone = JSON.parse(JSON.stringify(this.paymentMethodMap))
        console.log(this.paymentMethodMapClone)
        await Promise.all([this.getTreeData(), this.getOwnersList(temp.ckOrgId), this.getShowCsmCardValue()])
        this.init()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            if (temp.reStatus === 1) {
              this.$message('温馨提示：该单无需回执')
            }
            console.log('this.temp.fromPlat', this.temp.fromPlat)
            if (this.row.fromPlat === 2) {
              this.rules.depReceiver[0].required = false
            } else {
              this.rules.depReceiver[0].required = true
            }
            this.temp.reCheckUserName = this.userInfo.userName
            this.temp.orgSNNo = temp.ckOrgSNNo
            this.temp.orgId = temp.ckOrgId
            this.temp.orgName = temp.ckOrgName
            this.temp.depReceiver = temp.depReceiver
            this.detail = temp
            this.csmName = temp.csmName
            this.csmPhone = temp.csmPhone
            this.temp.paymentMethod = temp.paymentMethod
            this.$nextTick(() => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          }
        })
      },
      // 查询是否显示预付卡
      async getShowCsmCardValue() {
        // const idx = this.paymentMethodMapClone.findIndex(item => item.value === 8)
        // this.paymentMethodMapClone.splice(idx, 1) // 支付方式下拉框去掉优惠券
        // if (!this.showCsmCard) {
        //   const index = this.paymentMethodMapClone.findIndex(item => item.value === 256)
        //   this.paymentMethodMapClone.splice(index, 1) // 删除预付卡
        // }
      },
      init() {
        const data = this.paymentMethodMap
        let text = ''
        const values = []
        for (let i = 0; i < data.length; i++) {
          var item = data[i]
          if (item.value === -1) {
            continue
          }
          if (item.value & this.row.paymentMethod) {
            if (!text) {
              text += item.text
            } else {
              text += ','
              text += item.text
            }
            values.push(item.value)
          }
        }
        if (values.length === 1) {
          this.$set(this.temp, 'paymentMethod', this.row.paymentMethod)
          if (values[0] === 2 || values[0] === 32 || values[0] === 64 || values[0] === 128 || values[0] === 256 || values[0] === 512 || values[0] === 1024 || this.corpSettingData.sp6 >> 9 & 0x01) {
            this.payDisabled = true
          }
        }
      },
      // 支付方式改变
      async paymentChange(value) {
        // 支付方式修改,则重置预付卡验证状态
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', false)
        this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        // 预支付并且之前订单不是预付卡支付
        if (value === 256 && this.order.paymentMethod !== 256) {
          // 结束编辑
          if (this.tableData.data.some(item => item._edit)) {
            this.$message.warning('请结束编辑！')
            return
          }
          // 校验预支付账号是否存在,预支付金额是否足够支付
          this.selectCsmCardCodeByOrderCode()
        }
      },
      // 根据批发订单查询客户预付卡
      async selectCsmCardCodeByOrderCode() {
        const res = await queryCsmCardCodeByOrderCode({
          orderCode: this.detail.orderCode,
          billType: 1,
          payMoney: this.totalReflections
        })
        // 客户可用预付卡卡号
        // const cardCode = res.data.cardCode
        const checkWay = res.data.accCsmCardConfigInfo.checkWay
        // 规则配置不是无校验
        if (checkWay !== 1) {
          // 打开预付卡弹框
          this.$refs.prepaidCard.open(res.data)
        } else {
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_status', true)
          this.$set(this.check_csmCard_ok_info, 'check_csmCard_ok_msg', '')
        }
      },
      // 获取责任机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取详情数据
      async fetchData() {
        const res = await queryCashPledgeDetail({
          depCode: this.row.depositCode,
          depositId: this.row.depositId,
          depStatus: this.row.depStatus })
        this.temp = { ...res.data, ...this.temp }
        this.temp.depositrgPic = res.data.depositrgPic || ''
        this.tableData.data = res.data.depositDetails
        console.log(this.tableData.data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgId = value.orgId
        this.temp.paymentMethod = ''
        this.getOwnersList(value.orgId)
        this.$set(this.temp, 'depReceiver', '')
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
      },
      async success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const loading = this.$message({
            message: '正在提交',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          depositReceipt({ depositCode: this.temp.depositCode, depositrgPic: this.temp.depositrgPic }).then(() => {
            this.resolve()
            this.visible = false
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      async showSecondPayDialog() {
        // 二次支付前先验证是否支付成功，避免获取二维码失败
        const res = await queryCashPledgeDetail({
          depCode: this.row.depositCode,
          depositId: this.row.depositId,
          depStatus: this.row.depStatus })
        if (res.data && res.data.isRePay === 2) {
          return this.$message.warning('该押金单已二次支付成功，请勿重复支付')
        }
        // 打开二次支付
        this.$refs.secondPay.open(this.temp)
      },
      // 用于二次支付支付成功后自动调用回执确认接口 与success手动调用需区分
      success1() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          depositReceipt({ depositCode: this.temp.depositCode, depositrgPic: this.temp.depositrgPic })
        })
      },
      handleConfirmPaySuccess() {
        this.resolve()
        this.visible = false
      },
      // 规格型号列表
      async getGoodsSpecList() {
        const res = await querySpecListAll({
          currentPage: 1,
          pageSize: 999
        })
        this.specList = res.data.rows
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const noSumArray = [
            'rental',
            'deposit',
            'btNoIDS'
          ]
          if (noSumArray.includes(column.property)) {
            return
          }
          const values = data.map((item) => Number(item[column.property]))
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        })
        sums.forEach((v, index) => {
          // 规格型号和数量字段合计不补零
          if (index > 1 && index !== 3) {
            sums[index] = isNaN(sums[index] * 1)
              ? '0.00'
              : Number(sums[index] * 1).toFixed(2)
          }
        })
        return sums
      },
      uploadUrlChange(e) {
        console.log(e)
        this.temp.depositrgPic = e.url
      },
      reset() {
        this.$nextTick(() => {
          this.temp = {
            orgSNNo: '',
            depReceiver: '',
            paymentMethod: 1,
            reCheckUserName: '',
            depositrgPic: ''
          }
          this.tableData.data = []
          this.tableData.defaultData = []
          this.showCsmCard = false
          this.payDisabled = false
          this.visible = false
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.table {
  /deep/ .cell .right {
    display: inline-block;
    width: 100%;
    text-align: right;
  }
  /deep/ .el-input-number {
    width: 88px;
    padding-right: 5px;
    padding-left: 5px;
  }
}
.dialog-footer {
  .footer-tip {
    float: left;
    color: red;
  }
}
</style>
